package org.com.controller;

import org.com.common.R;
import org.com.pojo.Comments;
import org.com.pojo.CommentReplies;
import org.com.pojo.Plants;
import org.com.pojo.Users;
import org.com.service.CommentsService;
import org.com.service.CommentRepliesService;
import org.com.service.PlantsService;
import org.com.service.UsersService;
import org.com.util.AliOssUtil;
import org.com.vo.CommentVO;
import org.com.vo.ReplyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/plants")
public class PlantsController {

    private static final Logger log = LoggerFactory.getLogger(PlantsController.class);

    @Autowired
    private PlantsService plantsService;

    @Autowired
    private CommentsService commentsService;

    @Autowired
    private CommentRepliesService commentRepliesService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private AliOssUtil aliOssUtil;

    // 获取所有已发布的文章列表（所有用户可见）
    @GetMapping("/list")
    public R getPlantsList() {
        try {
            // 只获取状态为已发布(1)的文章
            List<Plants> plants = plantsService.lambdaQuery()
                    .eq(Plants::getStatus, 1)  // 只获取已发布的文章
                    .orderByDesc(Plants::getCreatedAt)
                    .list();
            return R.success("获取文章列表成功", plants);
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            return R.error("获取文章列表失败：" + e.getMessage());
        }
    }

    // 获取当前用户发布的所有文章（包括草稿和已发布）
    @GetMapping("/user/list")
    public R getUserPlantsList(HttpServletRequest request) {
        try {
            // 获取当前用户ID
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                return R.error("用户未登录");
            }
            Integer userId = (Integer) session.getAttribute("userId");
            
            // 获取该用户发布的所有文章（包括草稿和已发布）
            List<Plants> plants = plantsService.lambdaQuery()
                    .eq(Plants::getUserId, userId)  // 根据用户ID筛选
                    .orderByDesc(Plants::getCreatedAt)
                    .list();
            return R.success("获取我的文章列表成功", plants);
        } catch (Exception e) {
            log.error("获取用户文章列表失败", e);
            return R.error("获取我的文章列表失败：" + e.getMessage());
        }
    }

    // 管理员获取所有用户的所有文章（包括草稿和已发布）
    @GetMapping("/admin/list")
    public R getAllPlantsList() {
        try {
            // 获取所有用户的所有文章，包括草稿和已发布
            List<Plants> plants = plantsService.lambdaQuery()
                    .orderByDesc(Plants::getCreatedAt)
                    .list();
            return R.success("获取所有文章列表成功", plants);
        } catch (Exception e) {
            log.error("获取所有文章列表失败", e);
            return R.error("获取文章列表失败：" + e.getMessage());
        }
    }

    // 获取单个植物详情
    @GetMapping("/{plantId}")
    public R getPlantDetail(@PathVariable Integer plantId) {
        try {
            Plants plant = plantsService.getById(plantId);
            if (plant == null) {
                return R.error("文章不存在");
            }
            return R.success("获取文章详情成功", plant);
        } catch (Exception e) {
            return R.error("获取文章详情失败：" + e.getMessage());
        }
    }

    // 获取植物评论列表
    @GetMapping("/{plantId}/comments")
    public R getPlantComments(@PathVariable Integer plantId) {
        try {
            // 1. 获取评论列表
            List<Comments> comments = commentsService.lambdaQuery()
                    .eq(Comments::getPlantId, plantId)
                    .orderByDesc(Comments::getCreatedAt)
                    .list();
            
            // 2. 转换为VO并填充用户信息
            List<CommentVO> commentVOs = comments.stream().map(comment -> {
                CommentVO vo = new CommentVO();
                // 复制评论基本信息
                vo.setCommentId(comment.getCommentId());
                vo.setPlantId(comment.getPlantId());
                vo.setUserId(comment.getUserId());
                vo.setContent(comment.getContent());
                vo.setCreatedAt(comment.getCreatedAt());
                vo.setUpdatedAt(comment.getUpdatedAt());
                
                // 获取并设置用户信息
                Users user = usersService.getById(comment.getUserId());
                if (user != null) {
                    vo.setUserName(user.getUserName());
                    vo.setCallName(user.getCallName());
                    vo.setImageUrl(user.getImageUrl());
                }
                
                return vo;
            }).collect(Collectors.toList());
            
            return R.success("获取评论列表成功", commentVOs);
        } catch (Exception e) {
            log.error("获取评论列表失败", e);
            return R.error("获取评论列表失败：" + e.getMessage());
        }
    }

    // 添加植物评论
    @PostMapping("/{plantId}/comments")
    public R addComment(@PathVariable Integer plantId, @RequestBody Comments comment) {
        try {
            comment.setPlantId(plantId);
            comment.setCreatedAt(new Date());
            comment.setUpdatedAt(new Date());
            
            boolean success = commentsService.save(comment);
            if (success) {
                return R.success("评论添加成功");
            } else {
                return R.error("评论添加失败");
            }
        } catch (Exception e) {
            return R.error("评论添加失败：" + e.getMessage());
        }
    }

    // 获取评论的回复列表
    @GetMapping("/comments/{commentId}/replies")
    public R getCommentReplies(@PathVariable Integer commentId) {
        try {
            // 1. 获取回复列表
            List<CommentReplies> replies = commentRepliesService.lambdaQuery()
                    .eq(CommentReplies::getCommentId, commentId)
                    .orderByAsc(CommentReplies::getCreatedAt)
                    .list();
            
            // 2. 转换为VO并填充用户信息
            List<ReplyVO> replyVOs = replies.stream().map(reply -> {
                ReplyVO vo = new ReplyVO();
                // 复制回复基本信息
                vo.setReplyId(reply.getReplyId());
                vo.setCommentId(reply.getCommentId());
                vo.setUserId(reply.getUserId());
                vo.setContent(reply.getContent());
                vo.setCreatedAt(reply.getCreatedAt());
                
                // 获取并设置用户信息
                Users user = usersService.getById(reply.getUserId());
                if (user != null) {
                    vo.setUserName(user.getUserName());
                    vo.setCallName(user.getCallName());
                    vo.setImageUrl(user.getImageUrl());
                }
                
                return vo;
            }).collect(Collectors.toList());
            
            return R.success("获取回复列表成功", replyVOs);
        } catch (Exception e) {
            log.error("获取回复列表失败", e);
            return R.error("获取回复列表失败：" + e.getMessage());
        }
    }

    // 添加评论回复
    @PostMapping("/comments/{commentId}/replies")
    public R addReply(@PathVariable Integer commentId, @RequestBody CommentReplies reply) {
        try {
            reply.setCommentId(commentId);
            reply.setCreatedAt(new Date());
            
            boolean success = commentRepliesService.save(reply);
            if (success) {
                return R.success("回复添加成功");
            } else {
                return R.error("回复添加失败");
            }
        } catch (Exception e) {
            return R.error("回复添加失败：" + e.getMessage());
        }
    }

    // 删除评论
    @DeleteMapping("/comments/{commentId}")
    public R deleteComment(@PathVariable Integer commentId, HttpSession session) {
        log.info("收到删除评论请求，评论ID: {}", commentId);
        try {
            // 获取当前登录用户ID
            Integer userId = (Integer) session.getAttribute("userId");
            log.info("当前会话中的用户ID: {}", userId);
            
            if (userId == null) {
                log.warn("用户未登录，无法删除评论");
                return R.error("用户未登录");
            }

            // 查询评论是否存在且属于当前用户
            log.info("查询评论信息，commentId: {}, userId: {}", commentId, userId);
            Comments comment = commentsService.lambdaQuery()
                    .eq(Comments::getCommentId, commentId)
                    .eq(Comments::getUserId, userId)
                    .one();

            if (comment == null) {
                log.warn("评论不存在或不属于当前用户，commentId: {}, userId: {}", commentId, userId);
                return R.error("无权删除该评论或评论不存在");
            }

            log.info("开始删除评论，commentId: {}", commentId);
            // 删除评论
            int deleted = commentsService.getBaseMapper().deleteById(commentId);
            
            if (deleted > 0) {
                log.info("评论删除成功，开始删除相关回复");
                // 同时删除该评论下的所有回复
                boolean repliesDeleted = commentRepliesService.lambdaUpdate()
                        .eq(CommentReplies::getCommentId, commentId)
                        .remove();
                log.info("相关回复删除{}", repliesDeleted ? "成功" : "失败");
                
                return R.success("评论删除成功");
            } else {
                log.error("评论删除失败，commentId: {}", commentId);
                return R.error("评论删除失败");
            }
        } catch (Exception e) {
            log.error("删除评论过程中发生异常，commentId: " + commentId, e);
            return R.error("评论删除失败：" + e.getMessage());
        }
    }

    // 删除回复
    @DeleteMapping("/comments/replies/{replyId}")
    public R deleteReply(@PathVariable Integer replyId, HttpSession session) {
        try {
            // 获取当前登录用户ID
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                return R.error("用户未登录");
            }

            // 查询回复是否存在且属于当前用户
            CommentReplies reply = commentRepliesService.lambdaQuery()
                    .eq(CommentReplies::getReplyId, replyId)
                    .eq(CommentReplies::getUserId, userId)
                    .one();

            if (reply == null) {
                return R.error("无权删除该回复或回复不存在");
            }

            boolean success = commentRepliesService.removeById(replyId);
            if (success) {
                return R.success("回复删除成功");
            } else {
                return R.error("回复删除失败");
            }
        } catch (Exception e) {
            log.error("删除回复失败", e);
            return R.error("回复删除失败：" + e.getMessage());
        }
    }

    @PostMapping
    public R createArticle(HttpServletRequest request,
                          @RequestParam String name,
                          @RequestParam String description,
                          @RequestParam(required = false) MultipartFile image) {
        log.info("接收到创建文章请求");
        log.info("请求参数: name={}, description={}", name, description);
        if (image != null) {
            log.info("上传的图片信息: name={}, size={}, contentType={}", 
                image.getOriginalFilename(), 
                image.getSize(), 
                image.getContentType());
        }

        try {
            // 获取当前用户ID
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                log.warn("用户未登录，session为空或userId为空");
                return R.error("用户未登录");
            }
            Integer userId = (Integer) session.getAttribute("userId");

            // 上传图片到OSS（如果有图片）
            String imageUrl = null;
            if (image != null && !image.isEmpty()) {
                log.info("开始上传图片到OSS...");
                imageUrl = aliOssUtil.upload(image);
                log.info("图片上传成功，URL: {}", imageUrl);
            }

            // 创建文章对象
            Plants plant = new Plants();
            plant.setName(name);
            plant.setDescription(description);
            plant.setImageUrl(imageUrl);
            plant.setCreatedAt(new Date());
            plant.setUpdatedAt(new Date());
            plant.setUserId(userId);  // 设置发布者ID
            plant.setStatus(0);  // 设置状态为草稿

            // 保存文章
            log.info("准备保存文章信息: {}", plant);
            boolean saved = plantsService.save(plant);

            if (saved) {
                log.info("文章创建成功，plantId: {}", plant.getPlantId());
                return R.success("文章发布成功", plant);
            } else {
                log.warn("文章创建失败");
                return R.error("文章发布失败");
            }
        } catch (Exception e) {
            log.error("创建文章过程中发生异常", e);
            return R.error("文章发布失败：" + e.getMessage());
        }
    }

    // 管理员更新文章状态
    @PutMapping("/admin/{plantId}/status")
    public R updatePlantStatus(@PathVariable Integer plantId, @RequestParam Integer status) {
        try {
            if (plantId == null || status == null) {
                return R.error("文章ID和状态不能为空");
            }
            
            Plants plant = plantsService.getById(plantId);
            if (plant == null) {
                return R.error("文章不存在");
            }
            
            plant.setStatus(status);
            plant.setUpdatedAt(new Date());
            
            boolean success = plantsService.updateById(plant);
            if (success) {
                return R.success("更新文章状态成功");
            } else {
                return R.error("更新文章状态失败");
            }
        } catch (Exception e) {
            log.error("更新文章状态失败", e);
            return R.error("更新文章状态失败：" + e.getMessage());
        }
    }

    // 管理员删除文章
    @DeleteMapping("/admin/{plantId}")
    public R deletePlant(@PathVariable Integer plantId) {
        try {
            // 检查文章是否存在
            Plants plant = plantsService.getById(plantId);
            if (plant == null) {
                return R.error("文章不存在");
            }

            // 删除文章
            boolean success = plantsService.removeById(plantId);

            if (success) {
                return R.success("删除文章成功");
            } else {
                return R.error("删除文章失败");
            }
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return R.error("删除文章失败：" + e.getMessage());
        }
    }

    // 管理员更新文章
    @PutMapping("/admin/{plantId}")
    public R updatePlant(@PathVariable Integer plantId, @RequestBody Plants plant) {
        try {
            // 检查文章是否存在
            Plants existingPlant = plantsService.getById(plantId);
            if (existingPlant == null) {
                return R.error("文章不存在");
            }

            // 更新文章信息
            plant.setPlantId(plantId);
            plant.setUpdatedAt(new Date());
            boolean success = plantsService.updateById(plant);

            if (success) {
                return R.success("更新文章成功");
            } else {
                return R.error("更新文章失败");
            }
        } catch (Exception e) {
            log.error("更新文章失败", e);
            return R.error("更新文章失败：" + e.getMessage());
        }
    }
} 